package ua.kiev.tosik.price.modules.search.gui.models;

import ua.kiev.tosik.price.models.Prices;
import ua.kiev.tosik.price.modules.search.gui.PricesTable;

import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.util.Vector;

public class PricesTransferHandler extends TransferHandler {

	private PricesTable pricesTable;
	private Vector<Prices> pricesList;

	public PricesTransferHandler(PricesTable pricesTable) {
		this.pricesTable = pricesTable;
		pricesList = new Vector<Prices>();
	}

	@Override
	public int getSourceActions(JComponent c) {
		return COPY_OR_MOVE;
	}

	@Override
	public Transferable createTransferable(JComponent c) {
		pricesList.clear();
		JTable table = (JTable) c;
		int[] rows = table.getSelectedRows();
		for ( int row : rows ) {
			int convertedRow = table.convertRowIndexToModel(row);
			Prices p = pricesTable.getModel().getRow(convertedRow);
			if ( !p.isSelected() ) {
				pricesList.add(p);
			}
		}
		return new TransferablePrices(pricesList, rows);
	}

	@Override
	public boolean importData(JComponent c, Transferable t) {
		return true;
	}

	@Override
	public boolean canImport(JComponent c, DataFlavor[] flavors) {
		for (DataFlavor flavor : flavors) {
			if (TransferablePrices.pricesFlavor.equals(flavor)) {
				return true;
			}
		}
		return false;
	}

}